package com.ibp.service.impl;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ibp.service.FSHttpService;

import org.springframework.stereotype.Service;

@Service("httpServiceImpl")
public class FSHttpServiceImpl implements FSHttpService {

	private static Logger logger = LoggerFactory.getLogger(FSHttpServiceImpl.class);	  
	
	private PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

	//http客户端
	private  CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
	public FSHttpServiceImpl() {
		//new ConnectionCleaner(connectionManager).start();
	}
	
	
	/**
	 * get请求
	 * @param url
	 * @return
	 */
	public String sendGetRequest(String url){
		HttpGet httpGet = new HttpGet(url);
		String response = sendRequest(httpGet);
		return response ;
	}
	
	
	/***
	 * post请求
	 * @param url
	 * @return
	 */
	public String sendPostRequest(String url){
		HttpPost httpPost = new HttpPost(url);
		String response = sendRequest(httpPost);
		return response ;
	}
	
	/***
	 * post请求
	 * @param <T>
	 * @param url
	 * @return
	 */
	public String sendPostRequest(String url, List<NameValuePair> params){
		HttpPost httpPost = new HttpPost(url);		
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(params, Charset.forName("GB18030")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String response = sendRequest(httpPost);
		return response ;
	}
	
	/***
	 * 发送请求，并接收响应
	 * @param url
	 * @return
	 */
	public String sendRequest(HttpRequestBase request){
		CloseableHttpResponse response =null ;
		try {
			request.setHeader("Connection", "close");
			response = (CloseableHttpResponse) httpClient.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			String entityString = null ;
			if(statusCode == 200 ){
				HttpEntity entity = response.getEntity();
			    entityString = new String(EntityUtils.toString(entity, "GB18030"));	
			}
		    return entityString ;
		} catch (Exception e) {
			logger.error("http请求失败："+e);
		}finally{
			close(null,request,response);
		}
		return null ;
	}
	
    /***
     * 关闭HttpClient相关连接
     * @param httpClient
     * @param request
     * @param response
     */
	protected void close(CloseableHttpClient httpClient,HttpRequestBase request,CloseableHttpResponse response){
		if(request!=null){
			request.releaseConnection();
			logger.info("释放http请求...");
		}
		if(response!=null){
			try {
				response.close();
			} catch (IOException e) {
				logger.error("关闭CloseableHttpResponse连接失败："+e);
			}
		}
		if(httpClient != null){
			try {
				httpClient.close();
			} catch (IOException e) {
				logger.error("关闭httpClient连接失败："+e);
			}
		}
	}


	@Override
	public String sendPostRequest(String url, String paramsJson) {
		httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
		HttpPost httpPost = new HttpPost(url);
		try {
			StringEntity entity = new StringEntity(paramsJson, "GB18030");
			entity.setContentEncoding("GB18030"); 
			entity.setContentType("application/json");
			httpPost.setEntity(entity);			
		} catch (Exception e) {
			logger.error("发送post请求有异常：{}",e);
		}
		logger.debug("httpPost:{}",httpPost);
		String response = sendRequest(httpPost);
		return response ;
	}

	
	
}
